#include <stdint.h>
#include "Disc_V812.h"
#include "vme_sis.h"
#include "sis3100_vme_calls.h"

static const uint32_t THRESHOLD_REG	= 0x00;
static const uint32_t OUTPUTWIDTH_REG	= 0x40;
static const uint32_t DEADTIME_REG	= 0x44;
static const uint32_t MAJORITY_REG	= 0x48;
static const uint32_t INHIBIT_REG	= 0x4a;
static const uint32_t TESTPULSE_REG = 0x4c;
static const uint32_t VERSION_REG	= 0xfe;
static const uint32_t MODULE_REG	= 0xfc;
static const uint32_t FIXED_REG		= 0xfa;


void Disc_V812::SetThreshold(int channel, uint8_t value)
{
  threshold[channel] = value;
  vme_A24D16_write(handle, address + THRESHOLD_REG + 2*channel, value); 
}


void Disc_V812::SetInhibitPattern(uint16_t pattern)
{
  vme_A24D16_write(handle, address + INHIBIT_REG, pattern); 
}


void Disc_V812::SetOutputWidth(int chrange, uint8_t value)
{
  outputWidth[chrange] = value;
  vme_A24D16_write(handle, address + OUTPUTWIDTH_REG + 2*chrange, value); 
}


void Disc_V812::SetDeadTime(int chrange, uint8_t value)
{
  deadTime[chrange] = value;
  vme_A24D16_write(handle, address + DEADTIME_REG + 2*chrange, value); 
}


void Disc_V812::SetMajorityThreshold(uint8_t nchannels)
{
  //majorityThreshold = nchannels;
  unsigned int majthr = 12 * nchannels + nchannels / 2  - 6;
  vme_A24D16_write(handle, address + MAJORITY_REG, majthr); 
}


void Disc_V812::GenTestPulse()
{
  vme_A24D16_write(handle, address + TESTPULSE_REG, 0x00); 
}


uint16_t Disc_V812::GetManufacturerNumber()
{
  uint16_t code;
  vme_A24D16_read(handle, address +  MODULE_REG, &code);
  return code >> 10;
}


uint16_t Disc_V812::GetModuleType()
{
  uint16_t code;
  vme_A24D16_read(handle, address +  MODULE_REG, &code);
  return code & 0x3ff;
}


uint16_t Disc_V812::GetModuleVersion()
{
  uint16_t code;
  vme_A24D16_read(handle, address +  VERSION_REG, &code);
  return code >> 12;
}


uint16_t Disc_V812::GetSerialNumber()
{
  uint16_t code;
  vme_A24D16_read(handle, address +  VERSION_REG, &code);
  return code & 0xfff;
}


uint16_t Disc_V812::GetFixedCode()
{
  uint16_t code;
  vme_A24D16_read(handle, address +  FIXED_REG, &code);
  return code & 0xffff;
}
